<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/7
 * Time: 13:30
 */

namespace App\Services;
use App\Models\WechatQrcode;
use App\Models\WechatRequest;
use EasyWeChat\Support\Collection;
use EasyWeChat\Foundation\Application as EasyWeChat;
use App\Models\WechatFans;

class WechatEventService
{

    private $wechatQrcodeModel;
    private $wechatRequestModel;
    private $easyWechat;
    private $message;
    private $fromUser;
    private $wechatFansModel;

    public function __construct(WechatQrcode $wechatQrcode, WechatRequest $wechatRequest, WechatFans $wechatFans, EasyWeChat $easyWechat)
    {
        $this->wechatQrcodeModel = $wechatQrcode;
        $this->wechatRequestModel = $wechatRequest;
        $this->wechatFansModel = $wechatFans;
        $this->easyWechat = $easyWechat;
    }

    public function handle(Collection $message){
        $this->wechatRequestModel->create($message->toArray());
        $this->fromUser = $this->easyWechat->user->get($message->FromUserName);
        $this->message = $message;
        return $this->{$message->Event}();
    }

    public function SCAN(){
        $wechatQrcode = $this->wechatQrcodeModel->where("ticket", $this->message->Ticket)->first();
        $wechatQrcode->increment('scan_times');
        return $wechatQrcode->keyword;
    }

    public function subscribe(){
        $data = $this->fromUser->toArray();
        $data['tagid_list'] = json_encode($data['tagid_list']);
        $data['event_key'] = preg_replace("/[^\d]/","",$this->message->EventKey);
        $wechatQrcode = $this->wechatQrcodeModel->where("ticket", $this->message->Ticket)->first();

        //\Log::debug($data);
        $user = $this->wechatFansModel->where("openid",$data['openid'])->first();
        if($user){
            $user->update($data);
        }else{
            $wechatQrcode->scan_fans = $wechatQrcode->scan_fans + 1;
            $this->wechatFansModel->create($data);
        }
        $wechatQrcode->update();
        return $wechatQrcode->keyword;
    }

    public function unsubscribe(){
        return $this->wechatFansModel->where("openid",$this->fromUser->openid)->update(["subscribetime"=>0]);
    }

    public function __call($name, $arguments)
    {
        return new \EasyWeChat\Message\Transfer();
    }


}